package com.my.learn.design.producerAndConsumer;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class PrdCon01 {

    private BlockingQueue<String> blockingQueue = new ArrayBlockingQueue<>(20);


    public static void main(String[] args) throws InterruptedException {
        PrdCon01 prdCon01 = new PrdCon01();
        prdCon01.exect();
    }

    private void exect() throws InterruptedException {
        Thread thread01 = new Thread(new Producer());
        Thread thread02 = new Thread(new Consumer());
        thread01.start();
        Thread.sleep(1000);
        thread02.start();
    }

    private class Producer implements Runnable {

        public void add(String str) throws InterruptedException {
            blockingQueue.put(str);
        }

        @Override
        public void run() {
            try {
                for (int i = 0; i < 100; i++) {
                    add(i + "");
                    Thread.sleep(61);
                    System.out.println("生产:" + i + ",剩余:" + blockingQueue.size());
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private class Consumer implements Runnable {

        public String consumer() throws InterruptedException {
            return blockingQueue.take();
        }

        @Override
        public void run() {
            try {
                for (int i = 0; i < 100; i++) {
                    Thread.sleep(51);
                    System.out.println("消费:" + consumer() + ",剩余:" + blockingQueue.size());
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }
}
